package com.wing.user.controller.admin;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Editor;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.constant.GlobalConstants;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.redis.utils.redis.RedisHelperImpl;
import com.wing.user.model.entity.*;
import com.wing.user.model.response.DepartmentVO;
import com.wing.user.model.response.MenuBtnData;
import com.wing.user.model.response.MenuVO;
import com.wing.user.model.response.RoleAuthorityVO;
import com.wing.user.service.*;
import com.wing.user.utils.ExcelUtils;
import com.wing.web.excel.DownExcelUtil;
import com.wing.web.excel.ExcelUtil;
import com.wing.web.excel.RoleExcelIn;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author
 */
@Slf4j
@Api(value = "Admin-角色管理", tags = "#/user/role")
@RestController
@RequestMapping("/user/admin/role")
@RequiredArgsConstructor
public class RoleController {

    private final RoleService roleService;
    private final RoleMenuService roleMenuService;
    private final MenuService menuService;
    private final AuthorityService authorityService;
    private final RedisHelperImpl redisHelper;
    private final CompanyInfoService companyInfoService;
    private final DepartmentService departmentService;

    @ApiOperation(value = "查询所有角色", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyword", value = "搜索关键字", required = false, dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "sort", value = "排序字段名", defaultValue = "sort_number", example = "sort_number", dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "order", value = "排序规则(asc:正序, desc:倒序)", defaultValue = "desc", example = "desc", dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "companyInfoId", value = "企业ID", defaultValue = "", example = "", dataType = "Long", paramType = "query")
            , @ApiImplicitParam(name = "departmentId", value = "部门ID", defaultValue = "", example = "", dataType = "Long", paramType = "query")
            , @ApiImplicitParam(name = "name", value = "名称", defaultValue = "", example = "", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<Role> list(
            @RequestParam(defaultValue = "1") Integer page
            , @RequestParam(defaultValue = "10") Integer limit
            , @RequestParam(defaultValue = "sort_number") String sort
            , @RequestParam(defaultValue = "desc") String order
            , Long companyInfoId
            , Long departmentId
            , String name
            , String filterIds
            , String isProduce
    ) {
        Page<Role> pg = new Page<>(page, limit);
        Map<String,Object> paramMap = new HashMap();
        paramMap.put("sort", StrUtil.toUnderlineCase(sort));
        paramMap.put("order", StrUtil.toUnderlineCase(order));
        if (companyInfoId != null) {
            paramMap.put("companyInfoId", companyInfoId);
        }
        if (departmentId != null) {
            paramMap.put("departmentId", departmentId);
        }

        if(StringUtils.isNotBlank(isProduce)){
            paramMap.put("isProduce", isProduce);
        }
        if (StringUtils.isNotBlank(name)) {
            paramMap.put("name", name);
        }
        if (StringUtils.isNotBlank(filterIds)) {
            paramMap.put("filterIds", filterIds);
        }
        IPage<Role> list = roleService.pageList4app(pg, paramMap);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @GetMapping("/listAll")
    public List<Role> listAll(
            @RequestParam(defaultValue = "create_time") String sort
            , @RequestParam(defaultValue = "asc") String order
            , Long companyInfoId
            , String name
            , String filterIds
    ) {
        Map paramMap = new HashMap();
        paramMap.put("sort", StrUtil.toUnderlineCase(sort));
        paramMap.put("order", StrUtil.toUnderlineCase(order));
        if (companyInfoId != null) {
            paramMap.put("companyInfoId", companyInfoId);
        }
        if (StringUtils.isNotBlank(name)) {
            paramMap.put("name", name);
        }
        if (StringUtils.isNotBlank(filterIds)) {
            paramMap.put("filterIds", filterIds);
        }
        List<Role> list = roleService.list4app(paramMap);
        return list;
    }

    @GetMapping("/listAll2")
    public JsonResult<List<com.wing.user.model.request.Role>> listAll2(@RequestParam("name") String name) {
        Map paramMap = new HashMap();
        if (StringUtils.isNotBlank(name)) {
            paramMap.put("name", name);
        }
        List<Role> list = roleService.list4app(paramMap);
        return JsonResult.success(list);
    }


    @ApiOperation(value = "添加角色", notes = "添加")
    @PostMapping("/add")
    public JsonResult add(Role role) {
        //1
        if (roleService.save(role)) {
            MenuVO menuVO = menuService.getMenuByUrl();
            if (menuVO != null) {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(role.getId());
                roleMenu.setMenuId(menuVO.getId());
                roleMenu.setIsChecked(true);
                roleMenuService.save(roleMenu);
                List<Menu> menuList = menuService.list(new LambdaQueryWrapper<Menu>().eq(Menu::getParentId, menuVO.getId()));
                if (menuList.size() > 0) {
                    for (Menu menu : menuList) {
                        RoleMenu roleMenuTemp = new RoleMenu();
                        roleMenuTemp.setRoleId(role.getId());
                        roleMenuTemp.setMenuId(menu.getId());
                        roleMenuTemp.setIsChecked(true);
                        roleMenuService.save(roleMenuTemp);
                    }
                }
            }
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }

    @ApiOperation(value = "添加角色", notes = "添加")
    @PostMapping("/roleAdd")
    public JsonResult roleAdd(@RequestBody Role role) {
        if (roleService.save(role)) {
            MenuVO menuVO = menuService.getMenuByUrl();
            if (menuVO != null) {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(role.getId());
                roleMenu.setMenuId(menuVO.getId());
                roleMenu.setIsChecked(true);
                roleMenuService.save(roleMenu);
                List<Menu> menuList = menuService.list(new LambdaQueryWrapper<Menu>().eq(Menu::getParentId, menuVO.getId()));
                if (menuList.size() > 0) {
                    for (Menu menu : menuList) {
                        RoleMenu roleMenuTemp = new RoleMenu();
                        roleMenuTemp.setRoleId(role.getId());
                        roleMenuTemp.setMenuId(menu.getId());
                        roleMenuTemp.setIsChecked(true);
                        roleMenuService.save(roleMenuTemp);
                    }
                }
            }
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }

    @ApiOperation(value = "添加角色--复制而来", notes = "添加")
    @PostMapping("/addCopy")
    public JsonResult addCopy(@RequestBody Map map) {
        Role role = JSON.parseObject(JSON.toJSONString(map.get("role")), Role.class);
        if (roleService.save(role)) {//添加新角色
            List<RoleMenu> roleMenuList = roleMenuService.list(new QueryWrapper<RoleMenu>().eq("role_id", map.get("id")));//复制的角色
            List<RoleMenu> roleMenuListCopy = new ArrayList<>();
            for (int i = 0; i < roleMenuList.size(); i++) {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setIsChecked(roleMenuList.get(i).getIsChecked());
                roleMenu.setMenuButton(roleMenuList.get(i).getMenuButton());
                roleMenu.setMenuId(roleMenuList.get(i).getMenuId());
                roleMenu.setRoleId(role.getId());
                roleMenuListCopy.add(roleMenu);
            }
            if (roleMenuService.add(roleMenuListCopy)) {
                refreshRedis();
            }
            return JsonResult.success("保存成功");
        }
        return JsonResult.fail("保存失败");
    }

    @ApiOperation(value = "修改角色", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(Role role) {
        if (roleService.updateById(role)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }

    @ApiOperation(value = "修改角色", notes = "修改")
    @PutMapping("/updateRole")
    public JsonResult updateRole(@RequestBody Role role) {
        if (roleService.updateById(role)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }

    @ApiOperation(value = "删除角色", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色id", required = true, dataType = "String", paramType = "path")
    })
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long roleId) {
        roleService.delete(roleId);
        return JsonResult.success("删除成功");
    }

    @ApiOperation(value = "添加角色菜单", notes = "权限")
    @PostMapping("/addRoleMenu")
    public JsonResult addRoleMenu(@RequestBody List<RoleMenu> roleMenuList) {
        if (roleMenuService.add(roleMenuList)) {
            refreshRedis();
            return JsonResult.success("保存成功");
        }
        return JsonResult.fail("保存失败");
    }

    private void refreshRedis() {
        try {
            List<RoleAuthorityVO> roleAuthorityVOList = authorityService.authorityRoleList();
            if (CollectionUtil.isNotEmpty(roleAuthorityVOList)) {
                roleAuthorityVOList.stream().forEach(item -> {
                    String authority = item.getAuthority();
                    List<String> roles = item.getRoles();
                    //写入redis缓存
                    redisHelper.valuePut(GlobalConstants.URL_AUTH_ROLES_KEY + authority, roles);
                });
                //redis消息队列
                // redisTemplate.convertAndSend("cleanRoleLocalCache", "true");
            }
        } catch (Exception e) {
            log.error("refresh redis fail", e);
        }

    }

    @ApiOperation(value = "查询权限树", notes = "权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyword", value = "搜索关键字", dataType = "String", paramType = "query")
    })
    @GetMapping("/authTree")
    public JsonResult authTree(Long roleId) {
        Role role = roleService.getById(roleId);
        if (role == null) {
            return JsonResult.fail();
        }
        List<MenuVO> menuList = new ArrayList<>();
        if (role.getParentId() == -1L) {
            menuList = menuService.listAllMenuAndButton(roleId);
            Map<String, List<MenuBtnData>> menuMap = getMenuMap(menuList);
            List<MenuBtnData> rootList = menuMap.get("-1");
            constructMenuTree(rootList, menuMap);
            return JsonResult.success(rootList);
        } else {
            List<MenuVO> parentList = menuService.listAllMenuAndButton(role.getParentId());
            parentList = parentList.stream().filter(t -> t.getIsChecked()).collect(Collectors.toList());
            if(parentList.size() == 0){
                return JsonResult.fail("请先设置上级权限");
            }
            List<MenuVO> list = menuService.listAllMenuAndButton(role.getId());
            list = list.stream().filter(t -> t.getIsChecked()).collect(Collectors.toList());
            for (MenuVO menuVO : parentList) {
                menuVO.setIsChecked(false);
                menuVO.setCheckedBtns(null);
                MenuVO menu = list.stream().filter(t -> t.getId().longValue() == menuVO.getId().longValue()).findFirst().orElse(null);
                if (menu != null) {
                    menuVO.setIsChecked(menu.getIsChecked());
                    menuVO.setCheckedBtns(menu.getCheckedBtns());
                }
                menuList.add(menuVO);
            }
            Map<String, List<MenuBtnData>> menuMap = getMenuMap(menuList);
            List<MenuBtnData> rootList = menuMap.get("-1");
            constructMenuTree(rootList, menuMap);
            return JsonResult.success(rootList);
        }
    }

    private Map<String, List<MenuBtnData>> getMenuMap(List<MenuVO> list) {
        Map<String, List<MenuBtnData>> menuMap = new LinkedHashMap<>();
        list.forEach(e -> {
            if (e.getParentId() == 4l) {
                System.out.println();
            }
            if (menuMap.containsKey(e.getParentId().toString())) {
                MenuBtnData menuBtnData = new MenuBtnData();
                menuBtnData.setName(e.getName());
                menuBtnData.setValue(String.valueOf(e.getId()));
                menuBtnData.setChecked(e.getIsChecked());
                menuBtnData.setId(e.getId());
                menuBtnData.setParentId(e.getParentId());
                menuBtnData.setBtns(e.getButton());
                menuMap.get(e.getParentId().toString()).add(menuBtnData);
            } else {
                MenuBtnData menuBtnData = new MenuBtnData();
                menuBtnData.setName(e.getName());
                menuBtnData.setValue(String.valueOf(e.getId()));
                menuBtnData.setChecked(e.getIsChecked());
                menuBtnData.setId(e.getId());
                menuBtnData.setParentId(e.getParentId());
                menuBtnData.setBtns(e.getButton());
                List<MenuBtnData> tempList = new ArrayList<>();
                tempList.add(menuBtnData);
                menuMap.put(e.getParentId().toString(), tempList);
            }
            if (StringUtils.isNotBlank(e.getButton()) && StringUtils.isNotBlank(e.getUrl())) {
                String[] btns = e.getButton().split(",");
                List<MenuBtnData> tempList = new ArrayList<>();
                for (String btn : btns) {
                    MenuBtnData menuBtnData = new MenuBtnData();
                    menuBtnData.setName(btn);
                    menuBtnData.setValue(e.getId() + ":" + btn);
                    menuBtnData.setChecked(("," + e.getCheckedBtns() + ",").contains("," + btn + ","));
                    menuBtnData.setParentId(e.getId());
                    tempList.add(menuBtnData);
                }
                menuMap.put(e.getParentId() + "_" + e.getId(), tempList);
            }
        });
        return menuMap;
    }

    private void constructMenuTree(List<MenuBtnData> rootList, Map<String, List<MenuBtnData>> menuMap) {
        for (MenuBtnData menuBtnData : rootList) {
            if (menuBtnData.getId() != null && (menuMap.containsKey(menuBtnData.getId().toString()) || menuMap.containsKey(menuBtnData.getParentId() + "_" + menuBtnData.getId()))) {
                if (StringUtils.isNotBlank(menuBtnData.getBtns())) {
                    if (menuMap.containsKey(menuBtnData.getId().toString())) {
                        menuBtnData.setChildren(menuMap.get(menuBtnData.getId().toString()));
                        constructMenuTree(menuBtnData.getChildren(), menuMap);
                    } else {
                        menuBtnData.setChildren(menuMap.get(menuBtnData.getParentId() + "_" + menuBtnData.getId()));
                    }
                } else {
                    menuBtnData.setChildren(menuMap.get(menuBtnData.getId().toString()));
                    constructMenuTree(menuBtnData.getChildren(), menuMap);
                }

            }
        }
    }

    private List<Map<String, Object>> getAuthTree(List<MenuVO> menus, Long parentId, List<MenuVO> roleMenuList) {
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < menus.size(); i++) {
            MenuVO temp = menus.get(i);
            if (parentId.equals(temp.getParentId())) {
                Map<String, Object> map = new HashMap<>();
                map.put("name", temp.getName());
                map.put("value", temp.getId());
                List<Map<String, Object>> children = getAuthTree(menus, menus.get(i).getId(), roleMenuList);
                map.put("children", children);
                List<MenuVO> roleMenuVOList = CollUtil.filter(roleMenuList, (Editor<MenuVO>) menuVO -> {
                    if (temp.getName().equals(menuVO.getName())) {
                        return menuVO;
                    }
                    return null;
                });
                if (roleMenuList != null && roleMenuVOList.size() > 0) {
                    for (MenuVO roleMenu : roleMenuList) {
                        map.put("checked", roleMenu.getIsChecked());
                        break;
                    }
                }
                //添加按钮权限
                if (!StringUtils.isBlank(temp.getButton())) {
                    List<String> buttonList = CollUtil.distinct(StrUtil.split(temp.getButton(), ','));
                    List<String> objectList = CollUtil.getFieldValues(roleMenuVOList, "button", String.class);
                    for (String button : buttonList) {
                        Map<String, Object> bMap = new HashMap<>();
                        bMap.put("name", button);
                        bMap.put("value", temp.getId() + ":" + button);
                        List<String> authButtonList = new ArrayList<>();
                        for (String buttonStr : objectList) {
                            List<String> split = StrUtil.split(buttonStr, ',');
                            authButtonList = (List<String>) CollUtil.union(authButtonList, split);
                        }
                        boolean bChecked = CollUtil.contains(authButtonList, button);
                        bMap.put("checked", bChecked);
                        children.add(bMap);
                    }
                }
                //去除空菜单
                if (StringUtils.isBlank(temp.getUrl()) && children.size() <= 0) {
                    continue;
                }
                list.add(map);
            }
        }
        return list;
    }

    @ApiOperation(value = "检查唯一性")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "编码", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "Long", paramType = "query")
    })
    @GetMapping("/isOnly")
    public JsonResult isOnly(@RequestParam(name = "code", required = false) String code,
                             @RequestParam(name = "id", required = false) Long id) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(code)) {
            queryWrapper.eq("code", code);
        }
        if (id != null) {
            queryWrapper.ne("id", id);
        }
        int count = roleService.count(queryWrapper);
        return JsonResult.success(count == 0);
    }

    @ApiOperation(value = "检查唯一性")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名称", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "Long", paramType = "query")
    })
    @GetMapping("/isOnlyName")
    public JsonResult isOnlyName(@RequestParam(name = "name", required = false) String name,
                                 @RequestParam(name = "id", required = false) Long id,
                                 @RequestParam(name = "companyInfoId", required = false) Long companyInfoId,
                                 @RequestParam(name = "departmentId", required = false) Long departmentId) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.eq("name", name);
        }
        if (id != null) {
            queryWrapper.ne("id", id);
        }
        if (companyInfoId != null) {
            queryWrapper.eq("company_info_id", companyInfoId);
        }
        if (departmentId != null) {
            queryWrapper.eq("department_id", departmentId);
        }
        int count = roleService.count(queryWrapper);
        return JsonResult.success(count == 0);
    }

    @ApiOperation(value = "通过ids查询角色岗位数据")
    @PostMapping("/getRoleData")
    public JsonResult getRoleData(@RequestBody List<Long> ids) {
        return JsonResult.success("操作成功", roleService.getRoleData(ids));
    }

    @ApiOperation(value = "查询所有的部门")
    @GetMapping("/getRoleDepartment")
    public List<Role> getRoleDepartment() {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_produce", true);
        List<Role> roleList = roleService.list(queryWrapper);
        return roleList;
    }


    @ApiOperation(value = "查询部门岗位信息")
    @GetMapping("/getRoleAllMap")
    public JsonResult<List<Map<String,String>>> getRoleAllMap() {
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Role::getId, Role::getName);
        List<Role> list = roleService.list(queryWrapper);
        List<Map<String, String>> collect = list.stream().map(info -> {
            Map<String, String> map = new HashMap<>();
            map.put("id", info.getId().toString());
            map.put("name", info.getName());
            return map;
        }).collect(Collectors.toList());
        return JsonResult.success(collect);
    }


    /**
     * 下载岗位数据录入excel模板
     */
    @ApiOperation(value = "下载岗位数据录入excel模板")
    @GetMapping("/template")
    public void template(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String[] headerArr = {"企业", "上级部门", "名称", "编码", "层级性质", "社保基数", "公积金基数"};
        String[] indexArr = {"0", "1", "4"};
        List<String[]> downData = new ArrayList<>();
        //企业
        List<CompanyInfo> list = companyInfoService.list();
        String[] data = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            data[i] = list.get(i).getName();
        }
        downData.add(data);
        //上级部门
        List<Department> departmentList = departmentService.list();
        String[] departmentData = new String[departmentList.size()];
        for (int i = 0; i < departmentList.size(); i++) {
            departmentData[i] = departmentList.get(i).getName();
        }
        downData.add(departmentData);

        String[] data2 = new String[]{"部门", "岗位"};
        downData.add(data2);
        DownExcelUtil.createExcelTemplate(response, request, "岗位角色导入模板", Arrays.asList(headerArr), downData, Arrays.asList(indexArr));
    }

    /**
     * 导入excel
     */
    @ApiOperation(value = "导入excel")
    @PostMapping("/importExcel")
    public JsonResult importExcel(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return JsonResult.fail("导入文件为空！");
        }
        try {
            //获取原始的文件名
            String originalFilename = file.getOriginalFilename();
            String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
            ExcelUtil<RoleExcelIn> reader = new ExcelUtil<>();
            InputStream is = file.getInputStream();
            List<RoleExcelIn> list = reader.read(is, RoleExcelIn.class);
            if (CollectionUtils.isEmpty(list)) {
                return JsonResult.fail("请在表格中添加数据！");
            }
            roleService.importExcel(list);
        } catch (BusinessException e) {
            log.error("导入文件异常！异常信息:", e);
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            //e.printStackTrace();
            log.error("导入文件异常！异常信息:", e);
            return JsonResult.exception("导入文件异常！异常信息:" + e.getMessage());
        }
        return JsonResult.success("导入成功！");
    }

    @ApiOperation(value = "导出")
    @GetMapping("/export")
    public void export(HttpServletResponse response) {
        List<Map<String, Object>> headerList = new ArrayList<>();
        Map<String, Object> headParams = new HashMap();
        headParams.put("name", "名称");
        headParams.put("code", "编码");
        headParams.put("companyInfoName", "企业");
        headParams.put("departmentName", "部门");
        headParams.put("isProduceVal", "是否生产岗位");
        headParams.put("socialSecurityBase", "社保基数");
        headParams.put("providentFundBase", "公积金基数");
        headerList.add(headParams);
        Map<String, Object> params = new HashMap();
        List<RoleExcelIn> list = roleService.exportList(params);
        ExcelUtils.export(response, "岗位", list, RoleExcelIn.class, headerList);
    }

    @ApiOperation(value = "查询所有角色", notes = "查询")
    @GetMapping("/getAll")
    public JsonResult getAll() {
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name");
        List<Role> supplierInfoList = roleService.list(wrapper);
        return JsonResult.success(supplierInfoList);
    }

    @GetMapping("/getRoleInfoByName")
    public JsonResult<Role> getRoleInfoByName(@RequestParam(name = "name", required = false) String name,
                                              @RequestParam(name = "departmentId", required = false) Long departmentId
            , @RequestParam(name = "thirdPartyJobtitleId", required = false) Long thirdPartyJobtitleId
            , @RequestParam(name = "companyInfoId", required = false) Long companyInfoId) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.eq("name", name);
        }

        if (departmentId != null) {
            queryWrapper.eq("department_id", departmentId);
        }
        if (thirdPartyJobtitleId != null) {
            queryWrapper.eq("third_party_jobtitle_id", thirdPartyJobtitleId);
        }
        if (companyInfoId != null) {
            queryWrapper.eq("company_info_id", companyInfoId);
        }
        Role one = roleService.getOne(queryWrapper);
        return JsonResult.success(one);
    }

    @ApiOperation(value = "获取所有部门-下拉树")
    @GetMapping("/getTreeData")
    public JsonResult getTreeData(Long roleId,String companyInfoId) {
        return roleService.getTreeData(roleId);
    }

    @ApiOperation(value = "获取部门下的岗位列表")
    @GetMapping("/getPostData")
    public JsonResult getPostData(@RequestParam(name = "roleId", required = true) Long roleId) {
        List<Role> roleList = roleService.getRoleHierarchy(roleId);
        List<Role> resultList = roleList.stream().filter(t -> !t.getIsProduce()).collect(Collectors.toList());
        return JsonResult.success(resultList);
    }

    @ApiOperation(value = "获取当前角色")
    @GetMapping("/get")
    public JsonResult<com.wing.user.model.request.Role> get(@RequestParam("id") Long id) {
        return JsonResult.success(roleService.getById(id));
    }



    @ApiOperation(value = "同步钉钉部门数据")
    @GetMapping("/syncDingDeptToSysRole")
    public void syncDingDeptToSysRole()  throws Exception{
        roleService.syncDingDeptToSysRole();
    }

}
